package com.example.lottery.service.impl;

import com.example.lottery.common.errorcode.ServiceErrorCodeConstants;
import com.example.lottery.common.exception.ServiceException;
import com.example.lottery.common.utils.CaptchaUtil;
import com.example.lottery.common.utils.RedisUtil;
import com.example.lottery.common.utils.RegexUtil;
import com.example.lottery.service.VerificationCodeService;
import com.example.lottery.service.dto.MailDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class VerificationCodeServiceImpl implements VerificationCodeService {
    //区分不同业务下redis中的key
    private static final String VERIFICATION_CODE_PREFIX = "verificationCode_";
    private static final Long VERIFICATION_CODE_TIME = 120L;

    @Autowired
    private EmailServiceImpl emailService;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public void sendVerificationCode(String email) {
        //校验邮箱
        if (!RegexUtil.checkMail(email)) {
            throw new ServiceException(ServiceErrorCodeConstants.MAIL_ERROR);
        }

        //生成随机验证码
        String code = CaptchaUtil.getCaptcha(5);

        //发送验证码
        MailDTO mailDTO = new MailDTO();
        mailDTO.setToEmail(email);
        //标题
        mailDTO.setSubject("登录的验证码");
        //内容
        mailDTO.setContent("你的验证码是：" + code + ",您的验证码会在2分钟后过期,过期后请重新申请验证码！");
        emailService.sendSimpleMail(mailDTO);

        //缓存验证码
        redisUtil.set(VERIFICATION_CODE_PREFIX + email, code, VERIFICATION_CODE_TIME);


    }

    @Override
    public String getVerificationCode(String email) {
        //校验邮箱
        if (!RegexUtil.checkMail(email)) {
            throw new ServiceException(ServiceErrorCodeConstants.MAIL_ERROR);
        }

        //获取缓存的验证码
        return redisUtil.get(VERIFICATION_CODE_PREFIX + email);
    }
}
